<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm"/>
  </BasicModal>
</template>
<script lang="ts" setup>
import {ref, computed, unref} from 'vue';
import {BasicModal, useModalInner} from '@/components/Modal';
import {BasicForm, useForm} from '@/components/Form';
import {accountFormSchema} from './user.data';
import {getDeptTreeList} from "@/api/system/dept.ts"
import {getSystemUserInfo, postUser, putUser} from "@/api/system/user";

defineOptions({name: 'AccountModal'});

const emit = defineEmits(['success', 'register']);

const isUpdate = ref(true);
const userId = ref('');


const [registerForm, {setFieldsValue, updateSchema, resetFields, validate}] = useForm({
  labelWidth: 100,
  baseColProps: {span: 24},
  schemas: accountFormSchema,
  showActionButtonGroup: false,
  actionColOptions: {
    span: 23,
  },
});

const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
  resetFields();
  setModalProps({confirmLoading: false});
  isUpdate.value = !!data?.isUpdate;

  if (unref(isUpdate)) {
    userId.value = data.record.userId;
    let res = await getSystemUserInfo({id: data.record.userId})  //用户信息补充
    console.log({...data.record, ...res})
    setFieldsValue({
      ...data.record, ...res
    });
  }


  const deptIdTreeData = await getDeptTreeList();

  updateSchema([
    {
      field: 'password',
      show: !unref(isUpdate),
      required: !unref(isUpdate),
    },
    {
      field: 'userName',
      show: !unref(isUpdate),
      required: !unref(isUpdate),
    },
    {
      field: 'deptId',
      componentProps: {treeData: deptIdTreeData},
    }
  ]);
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));

async function handleSubmit() {
  try {
    const values = await validate();
    setModalProps({confirmLoading: true});
    // TODO custom api
    if (unref(isUpdate)) {
      await putUser({...values,userId:userId.value})
    } else {
      await postUser({...values})
    }
    closeModal();
    emit('success');
  } catch (e) {
    console.log(e, "捕获异常")
  } finally {
    setModalProps({confirmLoading: false});
  }
}
</script>
